package containersvc

import (
	"fmt"
	corev1 "gluenet/internal/agent/api/core/v1"
	"gluenet/internal/agent/driver/hostdriver"
)

func (svc *Service) CreateContainer(container *corev1.DockerContainer) corev1.CommonResp {
	var (
		err error
		// ContainerDetial is more suitable to store
		containerObj *corev1.DockerContainerObj
	)

	svc.injectGluenetEnv(container)
	ct, err := svc.dd.Create(&container.Spec)
	if err != nil {
		goto ErrProcess
	}

	if err != nil {
		goto ErrProcess
	}

	containerObj = &corev1.DockerContainerObj{
		GluenetMeta: container.GluenetMeta,
		Spec:        ct,
		Status:      corev1.NewState(),
	}

	containerObj.Ready()
	err = svc.objects.
		ObPut(
			container.GluenetGuid,
			container.GluenetKind,
			containerObj,
		).
		NotifyObserver()

	if err != nil {
		goto ErrProcess
	}

	return corev1.NewCommonSuccessRespWithData(containerObj)

ErrProcess:
	svc.logger.Errorf(err.Error())
	return corev1.NewCommonFailureResp(err.Error())
}

func (svc *Service) injectGluenetEnv(ct *corev1.DockerContainer) {
	// TODO: form global
	guidEnv := fmt.Sprintf("GUID=%s", ct.GluenetGuid)
	agentIpEnv := fmt.Sprintf("AGENT_HOST_IP=%s", hostdriver.GetHost().HostIP)
	agentPortEnv := fmt.Sprintf("AGENT_HOST_PORT=%s", `50080`)
	jaegerIpEnv := fmt.Sprintf("JAEGER_AGENT_HOST=%s", hostdriver.GetHost().HostIP)
	jaegerPortEnv := fmt.Sprintf("JAEGER_AGENT_PORT=%s", `6831`)

	envs := ct.Spec.Config.Env
	envs = append(envs, guidEnv, agentIpEnv, agentPortEnv, jaegerIpEnv, jaegerPortEnv)
	ct.Spec.Config.Env = envs

}

func (svc *Service) GetContainer(meta *corev1.GluenetMeta) corev1.CommonResp {
	obj, err := svc.objects.Get(meta.GluenetGuid, meta.GluenetKind)
	container, ok := obj.(*corev1.DockerContainerObj)

	if err != nil && !ok {
		goto ErrProcess
	}

	if container.Spec, err = svc.dd.Get(container.Spec.ID); err != nil {
		goto ErrProcess
	}

	// TODO: Update ContainerObj State

	return corev1.NewCommonSuccessRespWithData(container)

ErrProcess:
	svc.logger.Errorf(err.Error())
	return corev1.NewCommonFailureResp(err.Error())

}

func (svc *Service) DeleteContainer(meta *corev1.GluenetMeta) corev1.CommonResp {
	obj, err := svc.objects.Get(meta.GluenetGuid, meta.GluenetKind)
	container, ok := obj.(*corev1.DockerContainerObj)

	if err != nil && !ok {
		goto ErrProcess
	} else {
		container.Terminating()
	}

	if err = svc.dd.Delete(container.Spec.ID); err != nil {
		goto ErrProcess
	} else {
		container.Terminated()
	}

	if err = svc.objects.ObDelete(meta.GluenetGuid, meta.GluenetKind).NotifyObserver(); err != nil {
		goto ErrProcess
	}

	return corev1.NewCommonSuccessRespWithData(nil)

ErrProcess:
	svc.logger.Errorf(err.Error())
	return corev1.NewCommonFailureResp(err.Error())
}
